//
//  MCWebViewController.m
//  MClient
//
//  Created by  史正烨 on 10-8-27.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "MCWebViewController.h"
#import "MServerJsonDAO.h"


@implementation MCWebViewController
@synthesize strLinkEnableFlag, webView = webViewCtrl;

- (int)identiferId {
	return 0;
}

- (void)viewDidLoad {
	
	[super viewDidLoad];
	webViewCtrl = [[UIWebView alloc] initWithFrame:self.clientView.bounds];
	webViewCtrl.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|
	UIViewAutoresizingFlexibleRightMargin|
	UIViewAutoresizingFlexibleTopMargin|
	UIViewAutoresizingFlexibleBottomMargin|
	UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
	
	[self.clientView addSubview:webViewCtrl];
	
	webViewCtrl.delegate = self;
	webViewCtrl.scalesPageToFit = YES;
	webViewCtrl.userInteractionEnabled = YES;
	webViewCtrl.backgroundColor = [UIColor clearColor];
	//webViewCtrl.opaque = NO;
	strLinkEnableFlag = @"ENABLE";
	
	[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	
	webViewCtrl.frame = CGRectMake(0, 0, self.width, self.height);
}

- (void)dealloc {
	[webViewCtrl removeFromSuperview];
	[webViewCtrl release];
    [super dealloc];	
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
	NSURL *url = request.URL;
	NSString *urlString = url.absoluteString;
	if(navigationType == UIWebViewNavigationTypeLinkClicked && 
	   [strLinkEnableFlag isEqualToString:@"ENABLE"]) {
		NSMutableURLRequest *requests = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
		NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:[MServerJsonDAO getCookies]];
		[requests setAllHTTPHeaderFields:headers];
		
		MCWebViewController *webViewController = [[MCWebViewController alloc] init];
		NSString *serverUrl = [self.userDefaults.current_ServerUrl stringByAppendingString:@"/beapp/"];
		webViewController.strLinkEnableFlag = @"ENABLE";
		[self.navigationController pushViewController:[webViewController autorelease] animated:YES];
		if ([urlString hasPrefix:@"http"]) {
			[webViewController loadHTMLfromURL:urlString];
		}else {
			[webViewController loadHTMLfromURL:[serverUrl stringByAppendingString:urlString]];
		}
		return NO;
	}
	return YES;	
}

#pragma mark ---- UIWebView代理方法 ----
//开始加载数据
- (void)webViewDidStartLoad:(UIWebView *)webView { 
	[self.appDelegate startActivityIndicatorView];
}

//数据加载完
- (void)webViewDidFinishLoad:(UIWebView *)webView {
	[self.appDelegate stopActivityIndicatorView]; 
	
	self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}


- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)loadHTMLfromURL:(NSString*)strUrl {
	//url里面有空格时会读不出来，需要将空格换成转义字符
	urlRequest = [[NSURLRequest requestWithURL:
				   [NSURL URLWithString:
					[strUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"]]] retain];
	if ([strUrl hasPrefix:@"https"]) {
		[NSURLConnection connectionWithRequest:urlRequest delegate:self];
	} else {
		[webViewCtrl loadRequest:urlRequest];
		[urlRequest release];
	}
}

- (void)loadHTMLString:(NSString*)htmlString {
	
	//[myWebView loadHTMLString:htmlstring  baseURL:[NSURL fileURLWithPath:[ [NSBundle mainBundle] bundlePath]]];
	
	[webViewCtrl loadHTMLString:htmlString baseURL:nil];
}

#pragma mark ----------------------------https 允许--------------------------------
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
	return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
	if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
		//if ([trustedHosts containsObject:challenge.protectionSpace.host])
		[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
	
	[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[webViewCtrl loadRequest:urlRequest];
	[urlRequest release];
}

@end

@implementation MCFileWebViewController
@synthesize fileName;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	webViewCtrl.scalesPageToFit = NO;
	webViewCtrl.userInteractionEnabled = NO;
	
	NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
	NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
	[webViewCtrl loadHTMLString:fileContent baseURL:nil];
}


- (void)dealloc {
	[fileName release];
    [super dealloc];
}


@end